import * as xlsx from "xlsx";
import {ElLoading, ElMessage} from "element-plus";
import type {LoadingInstance} from "element-plus/es/components/loading/src/loading";

//"development"
export function getDevMode(): string {
    return import.meta.env.MODE;
}

/**
 * 把文件按照二进制进行读取
 * @param file
 * @returns
 */
const readFile = async (file: File) => {
    return new Promise(resolve => {
        let reader = new FileReader();
        reader.readAsBinaryString(file);
        reader.onload = ev => {
            resolve(ev.target?.result);
        }
        // console.log(reader);
    });
}

export const readExcelFile = async (file, sheetIndex = 0) => {
    let data = await readFile(file);
    let workbook = xlsx.read(data, {type: 'binary', raw: true, cellDates: true});
    let worksheet = workbook.Sheets[workbook.SheetNames[sheetIndex]];
    let tableData = xlsx.utils.sheet_to_json(worksheet);
    console.log("readExcelFile==", tableData);
    return tableData;
}

//带有混合表头的
export const readExcelFileWithMixCol = async (file, sheetIndex = 0) => {
    let fileData = await readFile(file);
    let workbook = xlsx.read(fileData, {type: 'binary', raw: true, cellDates: true});
    let worksheet = workbook.Sheets[workbook.SheetNames[sheetIndex]];
    // 获取工作表的合并单元格信息
    const merges = worksheet['!merges'] || [];

    const data = [];
    merges.forEach(merge => {
        const {s, e} = merge; // s 是开始位置，e 是结束位置
        const startCell = xlsx.utils.encode_cell({c: s.c, r: s.r}); // 转换开始单元格为字母数字表示法
        const endCell = xlsx.utils.encode_cell({c: e.c, r: e.r}); // 转换结束单元格为字母数字表示法
        const value = worksheet[startCell] ? worksheet[startCell].v : ''; // 获取合并区域的起始单元格的值
        for (let row = s.r; row <= e.r; row++) {
            for (let col = s.c; col <= e.c; col++) {
                if (row === s.r && col === s.c) {
                    // 处理合并区域的起始单元格，只记录一次值
                    data[row] = data[row] || [];
                    data[row][col] = value; // 设置值
                } else {
                    // 对于合并区域内的其他单元格，可以设置为空或者与起始单元格相同的值，取决于你的需求
                    data[row] = data[row] || [];
                    data[row][col] = ''; // 或者保持为 undefined，取决于你的具体需求和展示方式
                }
            }
        }
    });

    for (const key in worksheet) {
        if (key[0] === '!' || !isNaN(+key[0])) continue; // 跳过元数据和数字索引的键（通常是行数据）
        const cell = worksheet[key]; // 获取单元格对象
        const {c, r} = xlsx.utils.decode_cell(key); // 解码单元格位置
        if (!merges.some(merge => xlsx.utils.encode_cell(merge.s) === key)) { // 检查该单元格是否不在合并区域内
            data[r] = data[r] || []; // 确保行存在
            data[r][c] = cell.v; // 设置值
        }
    }
    console.log("readExcelFileWithMixCol==", data);
    let tableData = data.filter(item => item.length > 1)
    let tableHeaderList = tableData[0]
    tableData = tableData.filter((item, index) => index != 0).map((tableItemList, tableIndex) => {
        let tableItemObj = {}
        tableItemList.forEach((tableItemItem, tableItemItemIndex) => tableItemObj[tableHeaderList[tableItemItemIndex]] = tableItemItem)
        return tableItemObj
    })
    console.log("readExcelFileWithMixCol==", tableData)
    return tableData
}

//时间格式化
export function formatDate(date, formatStr = 'YYYY-MM-DD HH:MM:SS', addSecond = 43) {
    // console.log("formatDate", date.toLocaleDateString())
    date.setSeconds(date.getSeconds() + addSecond);
    const day = date.getDate().toString().padStart(2, '0');
    const month = (date.getMonth() + 1).toString().padStart(2, '0'); // 月份是从0开始的
    const year = date.getFullYear();
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    const seconds = date.getSeconds().toString().padStart(2, '0');
    formatStr = formatStr.toLowerCase()
    let formateDateStr = formatStr.replace("yyyy", year)
        .replace("mm", month).replace("dd", day)
        .replace("hh", hours).replace("mm", minutes)
        .replace("ss", seconds)
    // console.log("formateDateStr", formateDateStr)
    return formateDateStr
}

//格式处理方法
export const formatExcelDate = (excelDate) => {
    const date = new Date((excelDate - 25569) * 86400 * 1000);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0");
    const day = String(date.getDate()).padStart(2, "0");
    const hh = String(date.getHours()).padStart(2, '0');
    const mm = String(date.getMinutes()).padStart(2, '0');
    const ss = String(date.getSeconds()).padStart(2, '0');
    return `${year}/${month}/${day} ${hh}:${mm}:${ss}`;
}

//对比两个时间段
export const compareDateSpanFn = (checkDayItem, offDayItem) => {
    let list1 = [checkDayItem['开始时间'], checkDayItem['结束时间']]
    let list2 = [offDayItem['开始日期'], offDayItem['结束日期']]
    return compareDateSpan(list1, list2)
}

//对比两个时间段
export const compareDateSpan = (list1, list2) => {
    list1 = list1.map(item => new Date(item.replace(/\//g, '-')).getTime())
    list2 = list2.map(item => new Date(item.replace(/\//g, '-')).getTime())
    return list2[0] <= list1[0] && list2[1] >= list1[1]
}

export const showToast = (message, type: "success", placement: "center") => {
    ElMessage({message: message, type, placement,})
}

export const showLoading: LoadingInstance = () => {
    return ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })
}

//filterTableItemKeys:[17", 18, 30, 31]
//arrData:
// {
//     '17日': '事假/上午',
//     '18日': "事假",
//     '30日': "产假/下午",
//     '31日': "产假",
// }
export const getDayOffData = (filterTableItemKeys, arrData, tableItemIndex) => {
    // console.log("getDayOffData==", filterTableItemKeys, JSON.stringify(arrData))
    let arrObj = {}, arrObjPre = {dayKey: '', dayNum: '', dayOffType: '', dayOffFlag: ''}

    const getDayOffType = (arrItemValue) => {
        return arrItemValue.includes("/") ? arrItemValue.split("/")[0] : arrItemValue
    }

    const getDayOffFlag = (arrItemValue) => {
        return arrItemValue.includes("/") ? arrItemValue.split("/")[1] : ""
    }

    filterTableItemKeys.forEach(item => {
        let betweenDayOffTypeSame = getDayOffType(arrData[`${item}日`]) === arrObjPre.dayOffType
        let betweenDayOffFlagRight = getDayOffFlag(arrData[`${item}日`]) !== '下午' && arrObjPre.dayOffFlag !== '上午'
        if (Object.keys(arrObj).length === 0) {
            arrObj[item] = [item]
            arrObjPre.dayKey = item
        } else if (item === arrObjPre.dayNum + 1 && betweenDayOffTypeSame && betweenDayOffFlagRight) {
            let arrObjPreList = arrObj[arrObjPre.dayKey] ? arrObj[arrObjPre.dayKey] : []
            arrObj[arrObjPre.dayKey] = [...arrObjPreList, item]
        } else {
            arrObj[item] = [item]
            arrObjPre.dayKey = item
        }
        arrObjPre.dayNum = item
        arrObjPre.dayOffType = getDayOffType(arrData[`${item}日`])
        arrObjPre.dayOffFlag = getDayOffFlag(arrData[`${item}日`])
    })

    // console.log(arrObj) //{ '17': [ 17 ], '18': [ 18 ], '30': [ 30, 31 ] }

    const getDayOffNum = (dayList) => {
        return dayList.map(dayItem => arrData[`${dayItem}日`].includes("/") ? 0.5 : 1).reduce((total, value) => total + value)
    }
    //type:1 开始，2:结束
    const getDayOffTime = (dayList, type) => {
        if (type === 1) return arrData[`${dayList[0]}日`].includes("下午") ? `14:30:00` : `08:30:00`
        if (type === 2) return arrData[`${dayList[dayList.length - 1]}日`].includes("上午") ? `12:00:00` : `18:00:00`
    }
    // arrObj {
    //   '17': { '请假天数': 0.5, '开始时间': '17 8:30:00', '结束时间': '17 12:00:00' },
    //   '18': { '请假天数': 1, '开始时间': '18 8:30:00', '结束时间': '18 18:00:00' },
    //   '30': { '请假天数': 1.5, '开始时间': '30 14:30:00', '结束时间': '31 18:00:00' }
    // }
    Object.entries(arrObj).forEach(([key, value], index) => {
        arrObj[key] = {
            "id": `${arrData['员工编号']}_${key}`,
            "子序号": index + 1,
            '员工姓名': arrData['员工姓名'],
            '员工编号': arrData['员工编号'],
            '请假天数': getDayOffNum(value),
            '请假类型': getDayOffType(arrData[`${key}日`]),
            '开始时间': `${arrData['年份']}/${arrData['月份']}/${value[0]} ${getDayOffTime(value, 1)}`,
            '结束时间': `${arrData['年份']}/${arrData['月份']}/${value[value.length - 1]} ${getDayOffTime(value, 2)}`,
            "children": []
        }
    })
    return arrObj
}